package utils;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;

/**
 * @Author : Magic Jwz
 */
public class BaseDOUtils {

    public static final String UPDATE_TIME_FIELD = "updateTime";
    public static final String CREATE_TIME_FIELD = "createTime";

    private BaseDOUtils(){}

    public static void resetUpdateObj(Object o, List<String> fieldList){
        clearField(UPDATE_TIME_FIELD, o);
        clearField(CREATE_TIME_FIELD, o);

        if (!CollectionUtils.isEmpty(fieldList)) {
            fieldList.forEach(fieldName -> clearField(fieldName, o));
        }
    }

    public static void resetUpdateObj(Object o){
        resetUpdateObj(o, Collections.emptyList());
    }

    /**
     * 清空属性值
     * @param fieldName
     * @param o
     */
    private static void clearField(String fieldName, Object o) {
        try {
            Field field = o.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            ReflectionUtils.setField(field, o, null);
        }catch (Exception e) {
            //ignore
        }
    }

}
